<?php
/**
 * Created by : PhpStorm
 * User: DuFei
 * Date: 2020/9/7
 * Time: 13:59
 */

namespace app\utils;





use app\exception\ErrorCode;
use app\exception\OaException;
use app\models\CreateOrderParams;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class PayUtils
{

    public static function createOrder(CreateOrderParams $params) {
        $sendData = $params->toArray();
        $sign = self::signature($sendData,\Yii::$app->params["payKey"]);
        $sendData["sign"] = $sign;

        return "https://pay.fhyx.com/api/unifiedorder.html?".http_build_query($sendData);

        return   self::postToServer("http://pay.fhyx.com/api/unifiedorder.html",$sendData,true);

    }

    /**
     * @return Client
     */
    public static function createClient() {
        return new Client([
            "verify"=>false
        ]);
    }

    /**
     * @param $url
     * @param $params
     * @param $isGet
     * @return \Psr\Http\Message\ResponseInterface
     * @throws FhyxException
     */
    public static function postToServer($url,$params,$isGet=false) {

        try {
            if ($isGet) {
                $request = self::createClient()->get($url,[
                    "query"=>$params
                ]);

            } else {
                $request = self::createClient()->post($url,[
                    "form_params"=>$params
                ]);
            }
            $resp1 = $request->getBody()->getContents();

            print_r($resp1);die;
            die;
            if ($request->getStatusCode()!=200) throw new OaException(ErrorCode::PAY_ERR);
            $resp1 = str_ireplace('<script>location.href="',"",$resp1);
            $resp1 = str_ireplace('";</script>',"",$resp1);
            return $resp1;

        } catch (GuzzleException $e) {
            throw new OaException(ErrorCode::PAY_ERR);
        }

    }

    /**
     * @param array $params
     * @return bool|string
     */
    public static  function keySort($params = array())
    {
        if (!empty($params)) {
            $p = ksort($params);
            if ($p) {
                $str = '';
                foreach ($params as $k => $val) {
                    if ($val)
                    $str .= $k . '=' . $val . '&';
                }
                $strs = rtrim($str, '&');
                return $strs;
            }
        }
        return false;
    }

    /**
     * @param $queryArr
     * @param $privateKey
     * @return string
     */
    public static function signature($queryArr,$privateKey)
    {
        if (isset($queryArr["sign"]))   unset($queryArr["sign"]);
        $sigStr = self::keySort($queryArr);
        $signUrl = $sigStr . "&key=".$privateKey;
        return strtoupper(md5($signUrl));
    }


    public static  function signatureProgress($queryArr,$action = 'create',$privateKey,$exKey = 'signature')
    {
        foreach ($queryArr as $key => $value)
        {
            if (trim($value)==='')
            {
                unset($queryArr[$key]);
            }
            else
            {
                $queryArr[$key] = trim($value);
            }
        }
        $paramKeyArr = array_keys($queryArr);
        foreach ($paramKeyArr as $key => $value)
        {
            if (strtolower(trim($value)) == $exKey)  //把 signature这个key剔除
            {
                $signature = strtolower($queryArr[$value]);
                unset($paramKeyArr[$key]);
            }
        }
        arsort($paramKeyArr);

        foreach ($paramKeyArr as $value)
        {
            $sigStr .= isset($sigStr) ? '-'.$value.'-'.$queryArr[$value] : $value.'-'.$queryArr[$value];
        }


        if ($action == 'valid')
        {
            return md5($sigStr . $privateKey) == $signature;
        }
        else
        {
            //echo $sigStr . $privateKey;exit;
            return md5($sigStr . $privateKey) ;
        }
    }
}
